#!/bin/sh
#
#  MKARCH - Return platform architecture.  Assumes source-only tree and
#  that it's safe to just manually change links.

set -e

# Initialize the $iraf and environment.
if [ -z "$iraf" ]; then
  if [ -e "$HOME/.iraf/setup.sh" ]; then
    . "$HOME/.iraf/setup.sh"
  else
    . unix/hlib/setup.sh
  fi
else
    . "$iraf/unix/hlib/setup.sh"
fi


aarch=$(unix/hlib/irafarch.sh -actual)

if [ -e "$iraf/unix/bin.$aarch/mkpkg.e" ]; then
    # Assume we've got a system with binaries and can use MKPKG.
    use_mkpkg=1
else
    if [ -n "$IRAFARCH" ] && [ -e "$iraf/unix/bin.$IRAFARCH/mkpkg.e" ]; then
        use_mkpkg=1
    else
        # Change the links manually, but strip all binaries first.
        use_mkpkg=0
    fi
fi


# Parse the arguments.
if [ "$*" ]; then
    archs="$*"
else
    archs=$aarch
fi

echo "Archs='$archs'"

for arch in $archs; do
    echo "Making architecture: $arch"

    nbits=$(IRAFARCH=$arch $iraf/unix/hlib/irafarch.sh -nbits)
    endian=$(IRAFARCH=$arch $iraf/unix/hlib/irafarch.sh -endian)

    if [ "$use_mkpkg" = 1 ]; then
        mkpkg "$arch"
        (cd noao && mkpkg -p noao "$arch")
    else
	"$iraf/util/mkclean"

        mkdir -p "bin.$arch" "noao/bin.$arch" "unix/bin.$arch"
        ln -sf "bin.$arch" bin
        (cd noao && ln -sf "bin.$arch" bin)
        (cd unix && ln -sf "bin.$arch" bin)
        (cd unix && ln -sf "as.$arch" as)
    fi

    if [ "$nbits" = "64" ]; then
        (cd unix/hlib && \
	     ln -sf iraf64.h iraf.h && \
	     ln -sf mach64.h mach.h )
    else
        (cd unix/hlib && \
	     ln -sf iraf32.h iraf.h && \
	     ln -sf mach32.h mach.h)
    fi
    if [ "$endian" = "big" ]; then
        ( cd unix/hlib && ln -sf swapbe.h swap.h )
    else
        ( cd unix/hlib && ln -sf swaple.h swap.h )
    fi
done

if [ -e "$HOME/.iraf/arch" ]; then
    echo "$arch" > "$HOME/.iraf/arch"
fi
